package com.sy.simpleegg.mvp.model

import android.os.Environment
import com.sy.simpleegg.base.BaseModel
import com.sy.simpleegg.constant.Constant
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.http.HttpUtil
import com.sy.simpleegg.http.callback.UploadLogCallback
import com.sy.simpleegg.mvp.contract.LogManageContract
import com.sy.simpleegg.util.FileUtil
import com.sy.simpleegg.util.Preference
import kotlinx.coroutines.delay
import okhttp3.Call
import okhttp3.Response
import java.io.File
import java.io.IOException

class LogManageModel: BaseModel(), LogManageContract.Model {

    /**
     * 设备编号
     */
    private var devNumber: String by Preference(Constant.SETTING_DEVICE_NUMBER, "")

    override fun getLogDirs(): Array<String>? {
        return try {
            val diskPath = Environment.getExternalStorageDirectory().absolutePath
            val folder = diskPath + File.separatorChar + "logger"
            val logFile = File(folder)
            if (!logFile.exists()) {
                logFile.mkdirs()
            }
            val fileList: MutableList<String> = ArrayList()
            val files = logFile.listFiles()
            if (files != null) {
                for (file in files) {
                    if (file.isDirectory && file.name.length == 8) {
                        fileList.add(file.name)
                    }
                }
            }
            if (fileList.isNotEmpty()){
                val result: MutableList<String> = mutableListOf()
                for (i in 0 until fileList.size){
                    result.add(fileList[fileList.size - 1 - i])
                }
                return result.toTypedArray<String>()
            }
            null
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("获取日志路径异常：${e.message}")
            null
        }
    }

    override suspend fun uploadLog(date: String): Int{
        return try {
            val diskPath = Environment.getExternalStorageDirectory().absolutePath
            val folder = diskPath + File.separatorChar + "logger"
            val zipFilePath = FileUtil.prepareLogFile(folder, date, devNumber)
            logFile("日志压缩文件：$zipFilePath")
            var uploadResult = 2
            zipFilePath?.let {
                val zipFile = File(zipFilePath)

                logFile("压缩文件：${zipFile.absolutePath}")

                uploadResult = 0
                HttpUtil.uploadFile(zipFile, devNumber, object : UploadLogCallback() {
                    override fun fail(call: Call?, e: IOException?) {
                        logFile("上传日志文件失败：${e?.message}")
                        uploadResult = 2
                    }

                    override fun response(call: Call?, response: Response?) {
                        logFile("上传日志文件成功：${response?.message}")
                        uploadResult = 1
                    }
                })

                do {
                    delay(1000)
                }while (uploadResult == 0)

            }?: 2
            delay(2000)
            uploadResult
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            logFile("上传日志文件异常：" + e.message)
            2
        }
    }

}